﻿using System;
using System.Windows;
using System.Windows.Interactivity;
using System.Windows.Input;
using myLiveMesh.Views.WindowManager;
using System.Windows.Controls;

namespace myLiveMesh.Behavior.WindowManager
{
    public class topWindowBehavior : Behavior<FrameworkElement>
    {
        private Point _startDrag;

        public topWindowBehavior() { }

        protected override void OnAttached()
        {
            base.OnAttached();
            this.AssociatedObject.MouseLeftButtonDown += mouseLeftDownOnTop;
            this.AssociatedObject.MouseLeftButtonUp += mouseLeftUpOnTop;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
        }

        public void mouseLeftDownOnTop(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement side = sender as FrameworkElement;

            if (side != null)
            {
                Grid grid = side.Parent as Grid;
                if (grid != null)
                {
                    windowView win = grid.Parent as windowView;
                    if (win != null)
                    {
                        this._startDrag = e.GetPosition(win);
                        this.AssociatedObject.MouseMove += mouseMoveOnTop;
                        side.CaptureMouse();
                    }
                }
            }
        }

        public void mouseLeftUpOnTop(object sender, MouseButtonEventArgs e)
        {
            FrameworkElement side = sender as FrameworkElement;

            if (side != null)
            {
                side.ReleaseMouseCapture();
                this.AssociatedObject.MouseMove -= mouseMoveOnTop;
            }
        }

        public void mouseMoveOnTop(object sender, MouseEventArgs e)
        {
            FrameworkElement side = sender as FrameworkElement;

            if (side != null)
            {
                Grid grid = side.Parent as Grid;

                if (grid != null)
                {
                    windowView win = grid.Parent as windowView;
                    if (win != null)
                    {
                        Point point = e.GetPosition(win);
                        double deltaY = this._startDrag.Y - point.Y;
                        double deltaX = this._startDrag.X - point.X;

                        this._startDrag = point;
                        Canvas.SetLeft(win, Canvas.GetLeft(win) + point.X);
                        Canvas.SetTop(win, Canvas.GetTop(win) + point.Y);
                    }
                }
            }
        }
    }
}
